/***************************************************************************
 * 文件名：FMToolGroupCard
 * 功能：
 * 说明：
 * -------------------------------------------------------------------------
 * 创建时间：2025/7/22 9:38:23
 * 创建人：葛浩
 * 邮箱：2094733071@qq.com
 * =========================================================================
 *
 * 修改人：   
 * 修改时间：   
 * 修改说明：   
 ***************************************************************************/
using DevExpress.Utils.Serializing.Helpers;
using DevExpress.XtraBars.ToolbarForm;
using RunMethodLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Util;

namespace AuxiliaryTools
{
	public partial class FMToolGroupCard : UserControl
	{
		/// <summary>
		/// 控件尺寸
		/// </summary>
		private Size _FormSize;
		public Size FormSize
		{
			get { return _FormSize; }
			set { _FormSize = value; }
		}

		/// <summary>
		/// 分类名称
		/// </summary>
		private string _ClassificationName;
		public string ClassificationName
		{
			get { return _ClassificationName; }
			set { _ClassificationName = value; }
		}

		/// <summary>
		/// 工具列表
		/// </summary>
		private List<CustomToolControlModel> _CustomToolControlModels;
		public List<CustomToolControlModel> CustomToolControlModels
		{
			get { return _CustomToolControlModels; }
			set { _CustomToolControlModels = value; }
		}

		/// <summary>
		/// 已安装工具名称列表
		/// </summary>
		private List<ToolModel> _TooModels;
		public List<ToolModel> ToolNames
		{
			get { return _TooModels; }
			set { _TooModels = value; }
		}

		/// <summary>
		/// 构造
		/// </summary>
		/// <param name="toolModels">已安装工具名称列表</param>
		/// <param name="size">界面尺寸</param>
		/// <param name="classificationName"></param>
		/// <param name="customToolControlModels"></param>
		public FMToolGroupCard(List<ToolModel> toolModels, Size size, string classificationName, List<CustomToolControlModel> customToolControlModels)
		{
			InitializeComponent();
			_TooModels = toolModels;
			_FormSize = size;
			_ClassificationName = classificationName;
			_CustomToolControlModels = customToolControlModels;
		}

		private void FMToolGroupCard_Load(object sender, EventArgs e)
		{
			InitControl();
		}

		/// <summary>
		/// 初始化控件
		/// </summary>
		private void InitControl()
		{
			try
			{
				#region 赋值

				this.Size = _FormSize;
				labTitle.Text = _ClassificationName;

				#endregion 构建工具卡片

				_CustomToolControlModels = _CustomToolControlModels?.Where(p => p.ToolName != "").ToList();

				if (_CustomToolControlModels?.Count <= 0)
				{
					return;
				}

				//两列布局显示
				int width = (this.Width - 120) / 2;
				int height = 60;

				bool isExistData = _TooModels?.Count > 0;

				int j = 0;
				int locationY = 0;
				for (int i = 1; i <= _CustomToolControlModels.Count; i++)
				{
					var tool = _CustomToolControlModels[i - 1];
					if (tool == null || string.IsNullOrEmpty(tool.ToolName))
					{
						continue;
					}

					Size size = new Size(width, height);
					bool isRegistered = isExistData ? _TooModels.Any(p => p.Name == tool.ToolName) : false;

					int locationX = (i % 2) == 1 ? 10 : 20 + width;

					if (i > 2 && i % 2 == 1)
					{
						j++;
					}
					locationY = 5 + (j * 55);

					FMToolDetail userControl = new FMToolDetail(size, tool.ToolName, isRegistered, tool.ToolDesc, tool.MemoryStream);

					userControl.Location = new Point(locationX, locationY);
					userControl.Name = tool.ToolName;
					userControl.OptionEvent += (sender, e) =>
					{
						//检测是未安装程序还是已安装程序
						//已注册，打开
						if (isRegistered)
						{
							var model = _TooModels.FirstOrDefault(p => p.Name == tool.ToolName);
							if (model == null)
							{
								return;
							}

							#region 检测启动配置项

							//如果程序入口不为空，则启动对应的程序
							if (string.IsNullOrEmpty(model.ToolFileDir) || string.IsNullOrEmpty(model.ProgramEntrance))
							{
								return;
							}

							#endregion

							#region 执行启动程序

							//检测文件类型，判断是Exe文件还是dll
							bool isExeProgram = FileHelperUtil.IsProgramExe(model.ProgramEntrance);

							switch (model.StartMode)
							{
								case ProgramStartMode.IndependentThreads:
									{
										if (!isExeProgram)
										{
											MessageBox.Show($"{model.Name}工具配置有误,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//检测程序入口文件是否存在
										string programPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, model.ToolFileDir, model.ProgramEntrance);

										if (string.IsNullOrEmpty(programPath) || !File.Exists(programPath))
										{
											MessageBox.Show($"{model.Name}工具程序入口配置有误,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//启动程序
										Process.Start(programPath);

										break;
									}
								case ProgramStartMode.InterfaceCall:
									{
										//从程序入口配置中解析dll文件名称、调用入口
										var list = model.ProgramEntrance.Split(';');
										if (list == null || list.Count() == 0 || list.Length != 2)
										{
											MessageBox.Show($"{model.Name}工具程序入口配置有误,请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										string dllFileName = list[0];
										string callClassName = list[1];

										//检测程序入口文件是否存在
										string programPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, model.ToolFileDir, dllFileName);

										if (string.IsNullOrEmpty(programPath) || !File.Exists(programPath))
										{
											MessageBox.Show($"{model.Name}工具程序入口配置的Dll文件不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//获取接口实例
										var IRunMethod4SingleForms = RunMethodUtil.GetExecutes(programPath, callClassName);
										if (IRunMethod4SingleForms?.Count == 0)
										{
											MessageBox.Show($"{model.Name}调用点配置有误！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
											return;
										}

										//启动程序
										if (IRunMethod4SingleForms[0] is IRunMethod4SingleForm singleForm)
										{
											// 通过事件手动解析依赖项
											AppDomain.CurrentDomain.AssemblyResolve += (senderx, argsx) =>
											{
												string dependencyPath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, model.ToolFileDir), $"{new AssemblyName(argsx.Name).Name}.dll");
												return File.Exists(dependencyPath) ? Assembly.LoadFrom(dependencyPath) : null;
											};

											if (!MainFormOption.Search2BringToFront(singleForm.FormType))
											{
												IRunMethod4SingleForms[0].Execute();
											}
										}
										break;
									}
								default:
									return;
							}

							#endregion
						}
						else//未注册，下载
						{
							//发送请求至GDM,下载文件


						}
					};

					groupControl1.Controls.Add(userControl);
				}

				this.Height = locationY + 100 + labTitle.Height;

				#region 

				#endregion

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
	}
}
